<?php

namespace Home\Model;

use Home\Service\Crypto\WXBizMsgCrypt;
use Think\Model;
use User\Model\RecommendModel;
use Wap\Service\WechatService;

class WechatUserModel extends Model
{
    CONST STATUS_ACTIVE = 1;//正常、已发布
    CONST STATUS_DELETE = 9;//已删除

    private $_token = 'esm';
    private $_encodingAesKey = 'wY8pJ0tB3nOZytwVS2xyL3dU2V9NXY7ug3aOARBpX8Z';
    /*private $_appId = 'wx9fee8af7befe3df5';
    private $_appSecret = '1282128572e92b0e91d190b3bf882f02';*/
    private $_appId = 'wxb103d59ce45902a1';
    private $_appSecret = '98e730f1ba6750e1b83448c8c8c67551';

    private static $_ori_id_arr = [
        'gh_a23930ed76f9' => [
            'appid' => 'wx824209ad37ce2d97',
            'secret' => '5b81f41af47f5820376b5f9f94700b2f'
        ],
        'gh_576df6701140' => [
            'appid' => 'wxdf10595e239b13e4',
            'secret' => 'bb89a5b1ab1726409fccfb9d4e07238c'
        ],
    ];

    private static $_recommend_ori_id_arr = [
        'gh_7e8978b18a85' => [
            'appid' => 'wx9fee8af7befe3df5',
            'secret' => '1282128572e92b0e91d190b3bf882f02'
        ],
        'gh_41ccaad1207b' => [
            'appid' => 'wx0b39dc9177895804',
            'secret' => 'ef71bcb444898a47d0982200a76239ae'
        ],
        'gh_4af99a41f313' => [
            'appid' => 'wxd1890ad13d954b1f',
            'secret' => 'b8c4e49a6497d5965b02e478927acd63'
        ]
    ];

    //--获取公众号token--
    private function _getAccessToken($ori_id, $again = 0, $type = 0)
    {
        if ($type == 0) {
            $appid = self::$_ori_id_arr[$ori_id]['appid'];
            $secret = self::$_ori_id_arr[$ori_id]['secret'];
        } else {
            $appid = self::$_recommend_ori_id_arr[$ori_id]['appid'];
            $secret = self::$_recommend_ori_id_arr[$ori_id]['secret'];
        }

        if ($again == 1) {
            S($appid . "_access_token", "");
        }
        new WechatService($appid, $secret);
        $access_token = S($appid . "_access_token");
        return $access_token;
    }

    //---添加关注账户--
    private function _add_wxuser_tosql($ori_id, $open_id, $again = 0)
    {
        $s_access_token = S($ori_id . "_access_token");
        if (empty($s_access_token)) {
            $s_access_token = $this->_getAccessToken($ori_id);
        }
        $res = WechatService::wechat_user_info($s_access_token, $open_id);
        if (!empty($res['errcode']) && !$again) {
            $this->_getAccessToken($ori_id, 1);
            $this->_add_wxuser_tosql($ori_id, $open_id, 1);
            return;
        }
        if (!empty($res['unionid'])) {
            $data['open_id'] = $open_id;
            $data['ori_id'] = $ori_id;
            $data['union_id'] = $res['unionid'];
            M("wechat_user")->add($data);
        }
    }

    //--更新关注账户--
    private function _update_wxuser_tosql($ori_id, $open_id, $user_id, $again = 0)
    {
        $s_access_token = S($ori_id . "_access_token");
        if (empty($s_access_token)) {
            $s_access_token = $this->_getAccessToken($ori_id);
        }
        $res = WechatService::wechat_user_info($s_access_token, $open_id);
        if (!empty($res['errcode']) && !$again) {
            $this->_getAccessToken($ori_id, 1);
            $this->_update_wxuser_tosql($ori_id, $open_id, $user_id, 1);
            return;
        }
        if (!empty($res['unionid'])) {
            $data['status'] = self::STATUS_ACTIVE;
            M("wechat_user")->where("user_id=" . $user_id)->save($data);
        }
    }

    //---删除关注账户--
    private function _del_wxuser_tosql($ori_id, $open_id, $user_id, $again = 0)
    {
        $s_access_token = S($ori_id . "_access_token");
        if (empty($s_access_token)) {
            $s_access_token = $this->_getAccessToken($ori_id);
        }
        $res = WechatService::wechat_user_info($s_access_token, $open_id);
        if (!empty($res['errcode']) && !$again) {
            $this->_getAccessToken($ori_id, 1);
            $this->_del_wxuser_tosql($ori_id, $open_id, $user_id, 1);
            return;
        }
        if (!empty($res['openid'])) {
            $data['status'] = self::STATUS_DELETE;
            $res = M("wechat_user")->where("user_id=" . $user_id)->save($data);
        }
    }


    //---处理关注相关事件--
    public function subscribe_relate($msg)
    {
        $pattern_touser = '/<ToUserName><!\[CDATA\[([^\]]*)\]\]><\/ToUserName>/';
        preg_match($pattern_touser, $msg, $arr_touser);

        $pattern_event = '/<Event><!\[CDATA\[([^\]]*)\]\]><\/Event>/';
        preg_match($pattern_event, $msg, $arr_event);

        $pattern_openid = '/<FromUserName><!\[CDATA\[([^\]]*)\]\]><\/FromUserName>/';
        preg_match($pattern_openid, $msg, $arr_openid);

        //---检查是否在 任务宝活动中--
        if (!empty($arr_touser) && $arr_touser[1] && !empty($arr_openid) && $arr_openid[1]
            && !empty($arr_event) && (($arr_event[1] === "subscribe") || ($arr_event[1] === "unsubscribe"))
        ) {
            $res = $this->check_recommend($arr_touser[1], $arr_openid[1], $arr_event[1]);
            if ($res) {
                echo "success";
                return;
            }
        }

        //--判断如果是公众号列表中有用户关注，添加到数据库中--
        if (!empty($arr_touser) && array_key_exists($arr_touser[1], self::$_ori_id_arr)) {
            if (!empty($arr_event) && ($arr_event[1] === 'subscribe')) {
                if (!empty($arr_openid) && $arr_openid[1]) {

                    //--判断用户是否已经在数据库存在--
                    $cond['ori_id'] = $arr_touser[1];
                    $cond['open_id'] = $arr_openid[1];
                    $cond['status'] = self::STATUS_ACTIVE;
                    $user = M("wechat_user")->where($cond)->find();

                    if (!$user) {
                        $this->_add_wxuser_tosql($arr_touser[1], $arr_openid[1]);
                    } else {
                        $this->_update_wxuser_tosql($arr_touser[1], $arr_openid[1], $user['user_id']);
                    }

                }
            }
            if (!empty($arr_event) && ($arr_event[1] === 'unsubscribe')) {
                if (!empty($arr_openid) && $arr_openid[1]) {

                    //--判断用户是否已经在数据库存在--
                    $cond['ori_id'] = $arr_touser[1];
                    $cond['open_id'] = $arr_openid[1];
                    $cond['status'] = self::STATUS_ACTIVE;
                    $user = M("wechat_user")->where($cond)->find();

                    if ($user) {
                        $this->_del_wxuser_tosql($arr_touser[1], $arr_openid[1], $user['user_id']);
                    }

                }
            }
        }
        echo "success";
    }

    //--任务宝活动处理, 返回值：true有任务宝活动，false没有任务宝活动--
    public function check_recommend($ori_id, $openid, $event, $again = 0)
    {
        $cond['ori_id'] = $ori_id;
        $date = date("Y-m-d H:i:s");
        $cond['start_date'] = array("ELT", $date);
        $cond['end_date'] = array("EGT", $date);
        $cond['status'] = RecommendModel::STATUS_ACTIVE;
        $recommend = M("recommend")->where($cond)->find();
        if (empty($recommend)) {//--没有任务宝活动直接返回---
            return false;
        }
        //---1.数据关系添加，2.发送客服信息--

        $s_access_token = S($ori_id . "_access_token");
        if (empty($s_access_token)) {
            $s_access_token = $this->_getAccessToken($ori_id, 0, 1);
        }
        //---取关用户--
        $cond_user['ori_id'] = $ori_id;
        if ($event == "unsubscribe") {
            $cond_user['open_id'] = $openid;
            $user = M("wechat_user")->where($cond_user)->find();
            if (!empty($user)) {
                $data['status'] = RecommendModel::STATUS_DELETE;
                M("wechat_user")->where("user_id=" . $user['user_id'])->save($data);
            }
            return true;
        }

        $res = WechatService::wechat_user_info($s_access_token, $openid);
        if (!empty($res['errcode']) && !$again) {
            $this->_getAccessToken($ori_id, 1, 1);
            return $this->check_recommend($ori_id, $openid, $event, 1);
        }
        //---微信服务器未返回正确结果时返回--
        if (empty($res['openid'])) {
            return true;
        }

        //--未添加用户，直接添加用户信息--
        $cond_user['ori_id'] = $ori_id;
        $cond_user['union_id'] = $res['unionid'];
        $user = M("wechat_user")->where($cond_user)->find();
        $data['status'] = RecommendModel::STATUS_ACTIVE;

        if (empty($user)) {
            $data['open_id'] = $openid;
            $data['ori_id'] = $ori_id;
            $data['union_id'] = $res['unionid'];
            M("wechat_user")->add($data);

            //--2.2 发送客服信息--
            $this->send_msg($s_access_token, $openid, $recommend['picurl'], $recommend['desc'],
                $res['unionid'], $recommend['rec_id'], $res['headimgurl']);
            return true;
        }

        //--已添加用户--
        //--1. 已绑定用户，判断是否要跟新状态--
        if ($user["open_id"]) {
            if ($user['status'] != RecommendModel::STATUS_ACTIVE) {
                M("wechat_user")->where("user_id=" . $user['user_id'])->save($data);
            }
            //--发送客服信息--
            $this->send_msg($s_access_token, $openid, $recommend['picurl'], $recommend['desc'],
                $res['unionid'], $recommend['rec_id'], $res['headimgurl']);
            return true;
        }
        //---2.未绑定用户添加绑定相关数据,发送客服信息--
        $data['open_id'] = $openid;
        $data['status'] = RecommendModel::STATUS_ACTIVE;
        $model = M("wechat_user");
        $model->startTrans();
        $user_res = M("wechat_user")->where("user_id=" . $user['user_id'])->save($data);
        if (empty($user['rec_union_id'])) {
            if ($user_res) {
                //--发送客服信息--
                $this->send_msg($s_access_token, $openid, $recommend['picurl'], $recommend['desc'],
                    $res['unionid'], $recommend['rec_id'], $res['headimgurl']);
                $model->commit();
            } else {
                $model->rollback();
            }
            return true;
        }
        //---2.1 添加关联信息---
        /*$fp=fopen("Public/Uploads/lottery/20180816/1.txt","a");
        fwrite($fp,"添加关联信息 \r\n");
        fclose($fp);*/
        //---2.1.1 添加用户自身信息--
        $self_recommend = true;
        $cond_recommend_data['union_id'] = $res['unionid'];
        $cond_recommend_data['rec_id'] = $recommend['rec_id'];
        $cond_recommend_data['ori_id'] = $ori_id;
        $self_recommend_f = M("wuser_recommend")->where($cond_recommend_data)->find();
        if (empty($self_recommend_f)) {
            $recommend_data['union_id'] = $res['unionid'];
            $recommend_data['rec_id'] = $recommend['rec_id'];
            $recommend_data['ori_id'] = $ori_id;
            $self_recommend = M("wuser_recommend")->add($recommend_data);
        }

        //--2.1.2 添加推荐一级二级信息--
        $rec_recommend_1 = true;
        $rec_recommend_2 = true;
        $cond_rec_recommend['union_id'] = $user['rec_union_id'];
        $cond_rec_recommend['rec_id'] = $recommend['rec_id'];
        $cond_rec_recommend['ori_id'] = $ori_id;
        $rec_recommend_f = M("wuser_recommend")->where($cond_rec_recommend)->find();
        if (empty($rec_recommend_f)) {
            $rec_recommend_data['union_id'] = $user['rec_union_id'];
            $rec_recommend_data['rec_id'] = $recommend['rec_id'];
            $rec_recommend_data['ori_id'] = $ori_id;
            $rec_recommend_data['first_rec'] = 1;
            $rec_recommend_1 = M("wuser_recommend")->add($rec_recommend_data);
        } else {
            //--更新一级信息---
            $rec_recommend_1 = M("wuser_recommend")->where("id=" . $rec_recommend_f['id'])->setInc('first_rec', 1);

            //---更新二级信息--
            $cond_1_user_info['union_id'] = $self_recommend_f['rec_union_id'];
            $cond_1_user_info['ori_id'] = $ori_id;
            $rec_1_user_info = M("wechat_user")->where($cond_1_user_info)->find();
            if (!empty($rec_1_user_info) && $rec_1_user_info['rec_union_id']) {
                $cond_rec_recommend_2['union_id'] = $rec_1_user_info['rec_union_id'];
                $cond_rec_recommend_2['rec_id'] = $recommend['rec_id'];
                $cond_rec_recommend_2['ori_id'] = $ori_id;
                $rec_recommend_f_2 = M("wuser_recommend")->where($cond_rec_recommend_2)->find();
                if (empty($rec_recommend_f_2)) {
                    $rec_recommend_data_2['union_id'] = $rec_1_user_info['rec_union_id'];
                    $rec_recommend_data_2['rec_id'] = $recommend['rec_id'];
                    $rec_recommend_data_2['ori_id'] = $ori_id;
                    $rec_recommend_data['sec_rec'] = 1;
                    $rec_recommend_2 = M("wuser_recommend")->add($rec_recommend_data);
                } else {
                    $rec_recommend_2 = M("wuser_recommend")->where("id=" . $rec_recommend_f_2['id'])->setInc('sec_rec', 1);
                }
            }
        }
        if (!$user_res || !$self_recommend || !$rec_recommend_1 || !$rec_recommend_2) {
            $model->rollback();
            return true;
        }
        $model->commit();
        //--2.2 发送客服信息--
        $this->send_msg($s_access_token, $openid, $recommend['picurl'], $recommend['desc'],
            $res['unionid'], $recommend['rec_id'], $res['headimgurl']);
        return true;
    }

    //---发送客服信息--
    public function send_msg($s_access_token, $openid, $picurl, $desc, $unionid, $recid, $headurl)
    {
        $s_union_id = S("union_id");
        $time = time();
        if (empty($s_union_id)) {
            S("union_id", $time, "20");
        } else {
            if (($time - $s_union_id) < 20) {
                return;
            } else {
                S("union_id", $time, "20");
            }
        }

        $url = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $s_access_token . '&type=image';
        $get_img_url = $this->get_img($recid, $unionid, $picurl, $headurl);
        $json = array('media' => new \CURLFile(realpath($get_img_url)));
        $row = self::_curlPost($url, $json);
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $s_access_token;
        $post_data['touser'] = $openid;
        $post_data['msgtype'] = 'image';
        $post_data['image'] = ['media_id' => $row['media_id']];
        $post_data = json_encode($post_data);
        $pic_res = self::_curlPost($url, $post_data);
        unlink($get_img_url);
        if (!empty($desc)) {
            $text_post = '{
                "touser":"' . $openid . '",
                "msgtype":"text",
                "text":
                {
                    "content":"' . $desc . '"
                }
            }';
            self::_curlPost($url, $text_post);
        }
    }

    public function get_img($recid, $unionid, $picurl, $headurl)
    {
        $store_url = __DIR__ . "/../../../Public/Uploads/recommend/" . $recid . $unionid . ".jpg";
        $erweimaurl = "http://esm.zbxinmeiti.com/Wap/Recommend/code?rec_id=" . $recid . "&union_id=" . $unionid .
            "&url=" . "http://esm.zbxinmeiti.com/Wap/Recommend/code?rec_id=" . $recid . "&union_id=" . $unionid;//二维码
        $beijing = "http://esm.zbxinmeiti.com" . $picurl;//海报最底层得背景

        $beijing = imagecreatefromstring(file_get_contents($beijing));
//        $logourl = imagecreatefromstring(file_get_contents($headurl));
        $erweimaurl = imagecreatefromstring(file_get_contents($erweimaurl));
        $beijing_w = imagesx($beijing);
        $beijing_h = imagesy($beijing);
//        $logourl_w = imagesx($logourl);
//        $logourl_h = imagesy($logourl);
        $erweimaurl_w = imagesx($erweimaurl);
        $erweimaurl_h = imagesy($erweimaurl);

//        $logo_dst_x = 50;
//        $logo_dst_y = 50;
        $erweima_dst_x = ($beijing_w - $erweimaurl_w) / 2;
        $erweima_dst_y = $beijing_h - $erweimaurl_h - 50;

        $image_3 = imageCreatetruecolor($beijing_w, $beijing_h);
        imagecopyresampled($image_3, $beijing, 0, 0, 0, 0, $beijing_w, $beijing_h, $beijing_w, $beijing_h);
//        imagecopymerge($image_3, $logourl, $logo_dst_x, $logo_dst_y, 0, 0, $logourl_w, $logourl_h, 100);//左，上，右，下，宽度，高度，透明度
        imagecopymerge($image_3, $erweimaurl, $erweima_dst_x, $erweima_dst_y, 0, 0, $erweimaurl_w, $erweimaurl_h, 100);
        //生成图片
        imagepng($image_3, $store_url);//在浏览器上显示
        imagedestroy($image_3);
        return $store_url;
    }

    public static function get_img_show($recid, $unionid, $picurl, $headurl)
    {
        header("content-type:image/jpg;");
        $erweimaurl = "http://esm.zbxinmeiti.com/Wap/Recommend/code?rec_id=" . $recid . "&union_id=" . $unionid .
            "&url=" . "http://esm.zbxinmeiti.com/Wap/Recommend/code?rec_id=" . $recid . "&union_id=" . $unionid;//二维码
        $beijing = "http://esm.zbxinmeiti.com" . $picurl;//海报最底层得背景

        $beijing = imagecreatefromstring(file_get_contents($beijing));
        $erweimaurl = imagecreatefromstring(file_get_contents($erweimaurl));
        $beijing_w = imagesx($beijing);
        $beijing_h = imagesy($beijing);
        $erweimaurl_w = imagesx($erweimaurl);
        $erweimaurl_h = imagesy($erweimaurl);

        $erweima_dst_x = ($beijing_w - $erweimaurl_w) / 2;
        $erweima_dst_y = $beijing_h - $erweimaurl_h - 50;

        $image_3 = imageCreatetruecolor($beijing_w, $beijing_h);
        imagecopyresampled($image_3, $beijing, 0, 0, 0, 0, $beijing_w, $beijing_h, $beijing_w, $beijing_h);
        imagecopymerge($image_3, $erweimaurl, $erweima_dst_x, $erweima_dst_y, 0, 0, $erweimaurl_w, $erweimaurl_h, 100);
        //生成图片
        imagepng($image_3);//在浏览器上显示
        imagedestroy($image_3);
    }

    public static function _curlPost($url, $post_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, "CURL post");
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output, true);
        return $output;
    }
}

?>